import { defineStore } from 'pinia'
import { getSystemConfig, updateSystemConfig, getPaymentConfig, updatePaymentConfig, getAiConfig, updateAiConfig, testAiConnection } from '@/api/config'

export const useConfigStore = defineStore('config', {
  state: () => ({
    systemConfig: {},
    paymentConfig: {},
    aiConfig: {},
    loading: false
  }),

  actions: {
    // 获取系统配置
    async fetchSystemConfig() {
      this.loading = true
      try {
        const response = await getSystemConfig()
        this.systemConfig = response.data
        return response
      } catch (error) {
        console.error('获取系统配置失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 更新系统配置
    async updateSystemConfig(data) {
      try {
        const response = await updateSystemConfig(data)
        this.systemConfig = { ...this.systemConfig, ...data }
        return response
      } catch (error) {
        console.error('更新系统配置失败:', error)
        throw error
      }
    },

    // 获取支付配置
    async fetchPaymentConfig() {
      this.loading = true
      try {
        const response = await getPaymentConfig()
        this.paymentConfig = response.data
        return response
      } catch (error) {
        console.error('获取支付配置失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 更新支付配置
    async updatePaymentConfig(data) {
      try {
        const response = await updatePaymentConfig(data)
        this.paymentConfig = { ...this.paymentConfig, ...data }
        return response
      } catch (error) {
        console.error('更新支付配置失败:', error)
        throw error
      }
    },

    // 获取AI配置
    async fetchAiConfig() {
      this.loading = true
      try {
        const response = await getAiConfig()
        this.aiConfig = response.data
        return response
      } catch (error) {
        console.error('获取AI配置失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 更新AI配置
    async updateAiConfig(data) {
      try {
        const response = await updateAiConfig(data)
        this.aiConfig = { ...this.aiConfig, ...data }
        return response
      } catch (error) {
        console.error('更新AI配置失败:', error)
        throw error
      }
    },

    // 测试AI连接
    async testAiConnection() {
      this.loading = true
      try {
        const response = await testAiConnection()
        return response
      } catch (error) {
        console.error('测试AI连接失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    }
  }
})